// src/components/EmployeeFiles.js
import { Table, Button, Space, Input, Select, Modal, Form, message, Card, Divider, Upload, Row, Col, Typography, Statistic, Tag } from '@/utils/antd-imports';
import { SearchOutlined, FileAddOutlined, UploadOutlined, UserOutlined, SolutionOutlined, TeamOutlined, BankOutlined, FileTextOutlined, FolderOpenOutlined, ClockCircleOutlined } from '@/utils/icons';
import React, { useState } from 'react';





import DatePicker from 'antd/es/date-picker';













const { Search } = Input;
const { Option } = Select;
const { TextArea } = Input;
const { Text, Title } = Typography;

const EmployeeFiles = () => {
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  
  // 模拟档案数据
  const [dataSource, setDataSource] = useState([
    {
      key: '1',
      id: 'EMP20250001',
      name: '张三',
      department: '技术部',
      position: '前端开发',
      fileType: '人事档案',
      updateTime: '2025-10-15',
      manager: '李四',
      status: 'active',
      remark: '高级前端开发工程师'
    },
    {
      key: '2',
      id: 'EMP20250002',
      name: '王五',
      department: '市场部',
      position: '市场经理',
      fileType: '培训档案',
      updateTime: '2025-10-16',
      manager: '赵六',
      status: 'active',
      remark: '市场部负责人'
    },
    {
      key: '3',
      id: 'EMP20250003',
      name: '李华',
      department: '人事部',
      position: 'HR专员',
      fileType: '人事档案',
      updateTime: '2025-10-10',
      manager: '张总',
      status: 'active',
      remark: '负责招聘工作'
    },
    {
      key: '4',
      id: 'EMP20250004',
      name: '陈明',
      department: '财务部',
      position: '会计',
      fileType: '合同档案',
      updateTime: '2025-09-28',
      manager: '王总监',
      status: 'inactive',
      remark: '已离职'
    }
  ]);

  // 部门选项
  const departmentOptions = [
    '技术部',
    '市场部',
    '人事部',
    '财务部',
    '产品部',
    '运营部'
  ];

  // 档案类型选项
  const fileTypeOptions = [
    '人事档案',
    '培训档案',
    '绩效档案',
    '合同档案',
    '薪资档案'
  ];

  // 计算统计指标
  const calculateStats = () => {
    const totalFiles = dataSource.length;
    const activeFiles = dataSource.filter(file => file.status === 'active').length;
    const inactiveFiles = dataSource.filter(file => file.status === 'inactive').length;
    const recentUpdated = dataSource.filter(file => {
      const updateDate = new Date(file.updateTime);
      const now = new Date();
      return (now - updateDate) < 7 * 24 * 60 * 60 * 1000; // 最近7天更新的
    }).length;
    
    const departmentDistribution = {};
    dataSource.forEach(file => {
      departmentDistribution[file.department] = (departmentDistribution[file.department] || 0) + 1;
    });
    
    const mostCommonDept = Object.entries(departmentDistribution).sort((a, b) => b[1] - a[1])[0];
    
    return {
      totalFiles,
      activeFiles,
      inactiveFiles,
      recentUpdated,
      mostCommonDept: mostCommonDept ? `${mostCommonDept[0]} (${mostCommonDept[1]})` : '无数据'
    };
  };

  const stats = calculateStats();

  // 处理新建档案
  const handleCreate = () => {
    form.validateFields().then(values => {
      setLoading(true);
      // 模拟API调用
      setTimeout(() => {
        const newEmployee = {
          key: `EMP${Date.now()}`,
          id: `EMP${new Date().getFullYear()}${String(dataSource.length + 1).padStart(4, '0')}`,
          ...values,
          updateTime: new Date().toISOString().split('T')[0],
          status: 'active'
        };
        
        setDataSource([...dataSource, newEmployee]);
        message.success('档案创建成功');
        setLoading(false);
        setVisible(false);
        form.resetFields();
      }, 1000);
    }).catch(err => {
      console.log('验证失败:', err);
    });
  };

  // 处理删除档案
  const handleDelete = (key) => {
    setDataSource(dataSource.filter(item => item.key !== key));
    message.success('档案删除成功');
  };

  const columns = [
    {
      title: '员工编号',
      dataIndex: 'id',
      key: 'id',
      width: 150,
      fixed: 'left'
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 120,
      render: (text) => (
        <span>
          <UserOutlined style={{ marginRight: 8 }} />
          {text}
        </span>
      )
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
      width: 120,
      render: (text) => (
        <span>
          <BankOutlined style={{ marginRight: 8 }} />
          {text}
        </span>
      )
    },
    {
      title: '职位',
      dataIndex: 'position',
      key: 'position',
      width: 150
    },
    {
      title: '档案类型',
      dataIndex: 'fileType',
      key: 'fileType',
      width: 120,
      render: (text) => (
        <span>
          <SolutionOutlined style={{ marginRight: 8 }} />
          {text}
        </span>
      )
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 120,
      sorter: (a, b) => new Date(a.updateTime) - new Date(b.updateTime)
    },
    {
      title: '管理人',
      dataIndex: 'manager',
      key: 'manager',
      width: 120,
      render: (text) => (
        <span>
          <TeamOutlined style={{ marginRight: 8 }} />
          {text}
        </span>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (text) => (
        <Tag color={text === 'active' ? 'green' : 'red'}>
          {text === 'active' ? '有效' : '无效'}
        </Tag>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      fixed: 'right',
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" size="small">查看</Button>
          <Button type="link" size="small">下载</Button>
          <Button 
            type="link" 
            size="small" 
            danger
            onClick={() => handleDelete(record.key)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ];

  return (
    <div style={{ padding: 24 }}>
      <Card title={<Title level={3}>员工档案管理系统</Title>} bordered={false}>
        {/* 统计指标区域 */}
        <div style={{ overflowX: 'auto', marginBottom: 24 }}>
          <div style={{ display: 'flex', minWidth: 'max-content' }}>
            <div style={{ minWidth: '150px', marginRight: 16 }}>
              <Card size="small" style={{ textAlign: 'center' }}>
                <Statistic
                  title="档案总数"
                  value={stats.totalFiles}
                  prefix={<FileTextOutlined />}
                  valueStyle={{ color: '#1890ff', fontSize: '24px', fontWeight: 'bold' }}
                />
              </Card>
            </div>
            <div style={{ minWidth: '150px', marginRight: 16 }}>
              <Card size="small" style={{ textAlign: 'center' }}>
                <Statistic
                  title="有效档案"
                  value={stats.activeFiles}
                  prefix={<FolderOpenOutlined />}
                  valueStyle={{ color: '#52c41a', fontSize: '24px', fontWeight: 'bold' }}
                />
              </Card>
            </div>
            <div style={{ minWidth: '150px', marginRight: 16 }}>
              <Card size="small" style={{ textAlign: 'center' }}>
                <Statistic
                  title="无效档案"
                  value={stats.inactiveFiles}
                  prefix={<FolderOpenOutlined />}
                  valueStyle={{ color: '#f5222d', fontSize: '24px', fontWeight: 'bold' }}
                />
              </Card>
            </div>
            <div style={{ minWidth: '150px' }}>
              <Card size="small" style={{ textAlign: 'center' }}>
                <Statistic
                  title="最近更新"
                  value={stats.recentUpdated}
                  prefix={<ClockCircleOutlined />}
                  valueStyle={{ color: '#faad14', fontSize: '24px', fontWeight: 'bold' }}
                />
              </Card>
            </div>
          </div>
        </div>

        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={24}>
            <Card>
              <Text strong>档案分布: </Text>
              <Text>{stats.mostCommonDept}</Text>
            </Card>
          </Col>
        </Row>

        {/* 搜索和操作区域 */}
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
          <div>
            <Search
              placeholder="搜索员工姓名/编号"
              allowClear
              enterButton={<SearchOutlined />}
              style={{ width: 300, marginRight: 16 }}
            />
            <Select 
              placeholder="档案类型" 
              style={{ width: 150, marginRight: 16 }}
              allowClear
            >
              {fileTypeOptions.map(type => (
                <Option key={type} value={type}>{type}</Option>
              ))}
            </Select>
            <Select 
              placeholder="部门" 
              style={{ width: 150, marginRight: 16 }}
              allowClear
            >
              {departmentOptions.map(dept => (
                <Option key={dept} value={dept}>{dept}</Option>
              ))}
            </Select>
            <DatePicker 
              placeholder="更新时间" 
              style={{ width: 150 }} 
              allowClear
            />
          </div>
          <Button 
            type="primary" 
            icon={<FileAddOutlined />}
            onClick={() => setVisible(true)}
          >
            新建档案
          </Button>
        </div>

        {/* 档案表格 */}
        <Table 
          dataSource={dataSource} 
          columns={columns} 
          bordered
          pagination={{ pageSize: 10 }}
          scroll={{ x: 1300 }}
          rowKey="key"
        />

        {/* 新建档案模态框 */}
        <Modal
          title="新建员工档案"
          visible={visible}
          onOk={handleCreate}
          onCancel={() => {
            setVisible(false);
            form.resetFields();
          }}
          confirmLoading={loading}
          width={800}
        >
          <Form
            form={form}
            layout="vertical"
            initialValues={{
              status: 'active'
            }}
          >
            <Divider orientation="left">基本信息</Divider>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="name"
                  label="员工姓名"
                  rules={[{ required: true, message: '请输入员工姓名' }]}
                >
                  <Input placeholder="请输入员工姓名" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="department"
                  label="所属部门"
                  rules={[{ required: true, message: '请选择所属部门' }]}
                >
                  <Select placeholder="请选择所属部门">
                    {departmentOptions.map(dept => (
                      <Option key={dept} value={dept}>{dept}</Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="position"
                  label="职位"
                  rules={[{ required: true, message: '请输入职位' }]}
                >
                  <Input placeholder="请输入职位" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="manager"
                  label="管理人"
                  rules={[{ required: true, message: '请输入管理人' }]}
                >
                  <Input placeholder="请输入管理人姓名" />
                </Form.Item>
              </Col>
            </Row>

            <Divider orientation="left">档案信息</Divider>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="fileType"
                  label="档案类型"
                  rules={[{ required: true, message: '请选择档案类型' }]}
                >
                  <Select placeholder="请选择档案类型">
                    {fileTypeOptions.map(type => (
                      <Option key={type} value={type}>{type}</Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="status"
                  label="档案状态"
                >
                  <Select placeholder="请选择档案状态">
                    <Option value="active">有效</Option>
                    <Option value="inactive">无效</Option>
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            <Form.Item
              name="attachment"
              label="档案附件"
            >
              <Upload>
                <Button icon={<UploadOutlined />}>上传附件</Button>
              </Upload>
            </Form.Item>
            <Form.Item
              name="remark"
              label="备注"
            >
              <TextArea rows={3} placeholder="请输入备注信息" />
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </div>
  );
};

export default EmployeeFiles;